import {
  toast
} from '../utils/wxApi'

// 全局请求封装
const base_url = 'https://ceshiweb.picaime.com/';

export default (params, httpConfig = {}) => {
  let url = params.url;
  let method = params.method || "GET";
  let data = params.data || {};
  let header = {};
  const {
    showLoading,
    loadingText
  } = httpConfig;
  if (showLoading || loadingText) {
    wx.showLoading({
      title: loadingText || '加载中',
    })
  }
  if (method == "POST") {
    header = {
      'content-type': 'application/json'
    };
  }

  // 获取本地token
  const token = wx.getStorageSync("token");
  if (token) {
    header['token'] = token;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: base_url + url,
      method: method,
      header: header,
      data: data,
      success(response) {

        const res = response.data;
        console.log('请求success', res)
        if (response?.statusCode != 200) {
          reject(response)
          return errFn(response?.statusCode)
        }
        if (res.code == 200) {
          resolve(res);
        } else {
          reject(res)
          toast(res.msg || res.message || '出错啦，请稍后重试');
        }
      },
      fail(err) {
        console.log(err);
        console.log('请求fail', err)
        if (err.errMsg.indexOf('request:fail') !== -1) {
          wx.showToast({
            title: '网络异常',
            icon: "error",
            duration: 2000
          });
        } else {
          toast('未知异常');
        }
        reject(err);
      },
      complete() {
        if (showLoading || loadingText) wx.hideLoading();
      }
    });
  }).catch((e) => {});
};


function errFn(statusCode) {
  switch (statusCode) {
    case 401:
      // 保存当前页面路径和参数，用于登录后重定向
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (currentPage) {
        const route = currentPage.route;
        const options = currentPage.options;
        // 将路径和参数拼接
        let redirectUrl = `/${route}`;
        const params = Object.keys(options).map(key => `${key}=${options[key]}`).join('&');
        if (params) {
          redirectUrl += `?${params}`;
        }
        // 保存重定向信息
        wx.setStorageSync('redirectUrl', redirectUrl);
      }
      
      wx.showModal({
        title: "提示",
        content: "请登录",
        showCancel: false,
        success(res) {
          setTimeout(() => {
            wx.reLaunch({
              url: "/pages/index/index",
            });
          }, 1000);
        },
      });
      break;
    case 404:
      toast('请求地址不存在...');
      break;
    default:
      toast('请重试...');
      break;
  }
}